/*
 * @Date: 2020-02-17 12:36:46
 * @名称: 下载工具里的 开始下载
 * @版本: 0.01
 * @作者: 初雪桜
 * @邮箱: 202184199@qq.com
 * @最后编辑人: 初雪桜
 * @LastEditTime: 2020-08-23 00:23:02
 * @FilePath: /bica_acg/lib/tools/Controller/Download/PlayDownload.dart
 */
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:pica_acg/DataBaseFunction.dart';
import 'package:pica_acg/GlobalFunction.dart';
import 'package:pica_acg/GlobalKey.dart';
import 'package:pica_acg/GlobalSettings.dart';
import 'package:pica_acg/GlobalVarlable.dart';
import 'package:pica_acg/Pages/ComicsInfoDownload/Widget/ComicsInfoDownloadComicsInfoDownloadBottom/Widget/ComicsInfoDownloadComicsInfoDownloadBottomButton/ComicsInfoDownloadComicsInfoDownloadBottomButton.dart';
import 'package:pica_acg/tools/extends/Json/ComicsInfo/ComicsInfoListJson.dart'
    as comicsInfoListJson;

Map<String, dynamic> thread = Map(); // 线程数 越多这个变量数组下标越多
int beReady = 0; //当有一个线程下载完成这里+1

class PlayDownload {
  static void getDownLoad() async {
    // var file = Directory(sDocumentDir1);
    // file.delete(recursive: true);
    // return;
    for (var i = 0; i < $global_DownloadConcurrentNumber; i++) {
      //设置线程数
      thread["$i"] = Map();
    }
    var downloadImagesList = dataBaseSelect(
        'BookDownloadChapterImagesList', 'DownloadSuccess=?', [0],
        orderBy: ' ChapterId desc ');
    downloadImagesList.then((list) {
      // return;
      if (list.length > 0) {
        for (var i = 0;
            i < (list.length / ($global_DownloadConcurrentNumber)).ceil();
            i++) {
          for (var concurrent = 0;
              concurrent < $global_DownloadConcurrentNumber;
              concurrent++) {
            if (list.length >
                concurrent + ($global_DownloadConcurrentNumber * i)) {
              thread["$concurrent"]["$i"] =
                  list[concurrent + ($global_DownloadConcurrentNumber * i)];
            }
            // print(concurrent + ($global_DownloadConcurrentNumber * i));
          }
        }
        playDownload(downloadList: thread);
      } else {
        print('没有任何需要下载的内容');
      }
    });
  }

  static playDownload({Map<String, dynamic> downloadList}) async {
    //开始下载 判断是否传入了 downloadList 传入了则下载列表里的 没有传入则从数据裤继续下载
    if (downloadList == null) {
      print('全部下载完毕了');
    } else {
      if ($globalVarlableDownloadState) {
        print('早就开始下载啦 -- 重新获取下载列表');
        for (var i = 0; i < downloadList.length; i++) {
          sonThread(downloadList["$i"]);
        }
      } else {
        $globalVarlableDownloadState = true;
        for (var i = 0; i < downloadList.length; i++) {
          sonThread(downloadList["$i"]);
        }
        // downImages(bookId, chapterId, downloadInfo, callBack)
      }
    }
  }

  static void sonThread(Map downloadList, {page = 0}) {
    // 此刻这个downloadList里应该是这样的
    // {
    //   "id": 30,
    //   "BookId": "5c9b95b336bbd347145355a1",
    //   "ChapterId": "5db6f2e6559aae49bfa66cac",
    //   "ImagesName": "653cc9e0-1548-4cc3-bba0-d6e2e1bd9c18.jpg",//名字
    //   "SeverAddress": "http://sakura.nat300.top/4.jpg?",#服务器地址
    //   "PictureAliases": "4.jpg",#原名
    //   "AllImages": 26,
    //   "ThisIsImages": 3,
    //   "DownloadSuccess": 0z
    // };
    // for (var i = 0; i < downloadList.length; i++) {
    if (page < downloadList.length) {
      downImages(downloadList["$page"]['BookId'],
          downloadList["$page"]['ChapterId'], downloadList["$page"], (returnm) {
        if (returnm == true) {
          page = page + 1;
          sonThread(downloadList, page: page);
        }
      });
    } else {
      beReady++;
      if (beReady >= thread.length) {
        //当设置县城都下载完毕时 设置下载状态为假
        $globalVarlableDownloadState = false;
      }
    }

    // }
    /* 下载线程 */
  }

  static void downImages(
    String bookId,
    String chapterId,
    Map downloadInfo,
    Function callBack,
  ) async {
    // 此刻这个downloadInfo里应该是这样的
    // {
    //   "id": 30,
    //   "BookId": "5c9b95b336bbd347145355a1",
    //   "ChapterId": "5db6f2e6559aae49bfa66cac",
    //   "ImagesName": "653cc9e0-1548-4cc3-bba0-d6e2e1bd9c18.jpg",//名字
    //   "SeverAddress": "http://sakura.nat300.top/4.jpg?",#服务器地址
    //   "PictureAliases": "4.jpg",#原名
    //   "AllImages": 26,
    //   "ThisIsImages": 3,
    //   "DownloadSuccess": 0
    // };
    var sDocumentDir = (await getApplicationDocumentsDirectory());
    Dio dio = Dio();
    //判断断目录是否存在 不存在就创建
    var file = Directory(dataSpace + "/" + "Cartoon");
    bool exists = await file.exists();
    if (!exists) {
      await file.create();
      await Directory(dataSpace + "/" + "Cartoon/$bookId").create();
      await Directory(dataSpace + "/" + "Cartoon/$bookId/$chapterId").create();
    }
    file = Directory(dataSpace + "/" + "Cartoon/$bookId");
    exists = await file.exists();

    if (!exists) {
      await file.create();
      await Directory(dataSpace + "/" + "Cartoon/$bookId/$chapterId").create();
    }

    file = Directory(dataSpace + "/" + "Cartoon/$bookId/$chapterId");
    exists = await file.exists();

    if (!exists) {
      await file.create();
    }

    /*     try {
        // 读取文件
          final file = File(
              sDocumentDir1 + "/" + "Cartoon/$bookId/$chapterId" + '/123.json');
          String str = await file.readAsString();
          print(str);
        } catch (err) {
          print(err);
        } */
    try {
      // 下载文件
      var imagegDownInfo = {
        "isPath": (downloadInfo["IsPath"] == true) ? 1 : 0,
        "media": {
          "fileServer": downloadInfo['SeverAddress'],
          "path": downloadInfo['ImagesName'],
        },
      };

      await dio.download(
          imagesIsPath(comicsInfoListJson.Docs.fromJson(imagegDownInfo)),
          dataSpace +
              "/" +
              "Cartoon/$bookId/$chapterId/${downloadInfo['PictureAliases']}",
          onReceiveProgress: (int count, int total) {
        //进度
        // print("下载中 当前大小$count 总大小$total");
      });
      //!下载完成每一页都插入数据库
      dataBaseInsert('BookDownloadChapterInfo', {
        "BookId": bookId,
        "ChapterId": chapterId,
        "FileName": downloadInfo['PictureAliases'],
        "FileSrc":
            "/Cartoon/$bookId/$chapterId/${downloadInfo['PictureAliases']}",
      });
      dataBaseSelect("BookDownloadChapterList", 'BookId = ? and ChapterId = ?',
          [bookId, chapterId]).then((info) {
        if (info.length > 0) {
          if ($globalVarlableDownloadList["$bookId"] == null) {
            $globalVarlableDownloadList["$bookId"] = {
              "$chapterId": info[0]["Progress"]
            };
          } else {
            if ($globalVarlableDownloadList["$bookId"]['$chapterId'] == null) {
              $globalVarlableDownloadList["$bookId"]['$chapterId'] =
                  info[0]["Progress"];
            }
          }
          try {
            //更新下载窗口
            updateState(
              //更新状态
              bookId,
              chapterId,
              downloadInfo['AllImages'],
            );
          } catch (e) {
            print('更新下载状态失败错误信息' + e.toString());
          }
          dataBaseUpdate(
            "BookDownloadChapterList",
            {
              "Download": true,
              "Progress": $globalVarlableDownloadList["$bookId"]['$chapterId'],
              "Success":
                  ($globalVarlableDownloadList["$bookId"]['$chapterId'] == 1)
                      ? true
                      : false,
            },
            'BookId = ? and ChapterId = ?',
            [bookId, chapterId],
          );

          dataBaseUpdate(
            'BookDownloadChapterImagesList',
            {
              "DownloadSuccess": true,
            },
            'id = ? and ImagesName = ? and SeverAddress = ? and PictureAliases = ? and AllImages = ? and ThisIsImages = ?',
            [
              downloadInfo["id"],
              downloadInfo["ImagesName"],
              downloadInfo["SeverAddress"],
              downloadInfo["PictureAliases"],
              downloadInfo["AllImages"],
              downloadInfo["ThisIsImages"]
            ],
          );
          callBack(true);
        } else {
          print('发生意外错误');
        }
      });
    } on DioError catch (e) {
      print('downloadFile error---------$e');
      downImages(bookId, chapterId, downloadInfo, callBack); //如果下载失败重新下
    }
    Stream<FileSystemEntity> entityList =
        sDocumentDir.list(recursive: true, followLinks: false);
    // await for (FileSystemEntity entity in entityList) {
    //   //文件、目录和链接��继承自FileSystemEntity
    //   //FileSystemEntity.type静态函数返回值为FileSystemEntityType
    //   //FileSystemEntityType有三个常量：
    //   //Directory、FILE、LINK、NOT_FOUND
    //   //FileSystemEntity.isFile .isLink .isDerectory可用于判断类型
    //   print(entity.path);
    // }
  }
}

bool updateState(String bookId, String chapterId, int downloadInfo) {
  $globalVarlableDownloadList["$bookId"]['$chapterId'] =
      $globalVarlableDownloadList["$bookId"]['$chapterId'] + (1 / downloadInfo);
/**
 * !这里有问题
 * ?注意 这里会下载完成进行通知刷新页面 但是有的页面没载入 会导致刷新失败 代码就此不再执行所以要用try 保证出错就出错了 继续执行下面的
 */
// 如果       listKey 没载入 他会报错
  var progress = $globalVarlableDownloadList["$bookId"]['$chapterId'];
  print("我的print名称为modifyBlockLocation -zero " + chapterId);
  if (progress == 1.0) {
    downList[bookId][chapterId]["Color"] = {
      'Color': Color(0xff00a656),
      'TextColor': Color(0xffffffff),
    };
    print("我的print名称为modifyBlockLocation -a " + chapterId);
    downList[bookId][chapterId]["Extends"] = {
      "Download": true,
      "Success": true,
      "Progress": progress,
      "SetProgress": true,
    };
    print("我的print名称为modifyBlockLocation -b " + chapterId);
  } else {
    downList[bookId][chapterId]["Extends"] = {
      "Download": true,
      "Success": false,
      "Progress": progress,
      "SetProgress": true,
    };
    print("我的print名称为modifyBlockLocation -c " + chapterId);
  }

  try {
    //下载详细页面的通知
    comicsInfoComicsInfoBodyModule4SubsectionState.currentState
        .modifyBlockLocation();
  } catch (e) {
    // print('更新本子详情窗口下载进度时出现意外 错误行' +
    //     StackTrace.current.toString() +
    //     e.toString() +
    //     '可能原因 下载页面 comicsInfoComicsInfoBodyModule4SubsectionState 没载入');
    print('更新本子详情窗口下载进度时出现意外');
  }

  try {
    listKey.currentState.modifyBlockLocation();
  } catch (e) {
    // print('更新下载页面窗口下载进度时出现意外 错误行' +
    //     StackTrace.current.toString() +
    //     e.toString() +
    //     '可能原因 下载页面 listKey 没载入');
    print('更新下载页面窗口下载进度时出现意外');
  }

  try {
    //下载详细页面的通知
    downloadDownloadBodyDownloadDownloadListControllerState.currentState
        .updataDownloadProgress(bookId, chapterId);
  } catch (e) {
    print('更新下在窗口出现意外');
  }
  return true;
}
